<template>
  <div>
    <!-- 查询 -->
    <div class="mt-4">
      <el-form inline>
        <el-row>
          <el-col :span="8">
            <el-form-item>
              <el-input placeholder="输入房间号或客户姓名" v-model="searchKeyword" clearable @clear="getDesign">
                <template #append>
                  <el-button :icon="Search" @click="getDesign" />
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>

        </el-row>

        <el-row>

          <el-col :span="3" >
            <el-form-item label="楼层">
              <el-select v-model="round" style="width: 100px" @change="getDesign">
                <el-option
                    v-for="(floor, index) in floors"
                    :key="index"
                    :label="floor.label"
                    :value="floor.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="7" >
            <img src="@/images/bed_free.svg" style="width: 25px" alt="没人使用" />
            <span style="margin-left: 5px">空床位</span>
            <img
                src="@/images/bed_out.svg"
                style="width: 25px; margin-left: 15px"
                alt="外出"
            />
            <span style="margin-left: 5px">外出</span>
            <img
                src="@/images/bed_exist.svg"
                style="width: 25px; margin-left: 15px"
                alt="有人使用"
            />
            <span style="margin-left: 5px">有人</span>
          </el-col>
        </el-row>
      </el-form>

      <el-divider />

      <!-- 床位数据可视化 -->
      <div>
        <div class="show_box" v-if="record && record.room">
          <el-card
              shadow="hover"
              class="room"
              style="background-color: #409EFF"
          >
            <span>卫生间</span>
            <div style="margin-top: 50%; margin-left: 23%">
              <img src="@/images/human-male-female.svg" width="40px" alt="卫生间" />
            </div>
          </el-card>

          <!-- 遍历房间 -->
          <el-card
              shadow="hover"
              class="room"
              v-for="r in record.room"
              :key="r.roomNo"
          >

            <!-- 遍历床位 -->
            <div class="bed" v-for="b in r.bed" :key="b.bedName">
              <div class="bed_container" @click="openInfoDialog(b)">
                <img
                    v-if="b.statue === 1"
                    src="@/images/bed_free.svg"
                    width="30px"
                    style="margin-left: 8px"
                    alt="空闲"
                />
                <img
                    v-if="b.statue === 2"
                    src="@/images/bed_exist.svg"
                    width="30px"
                    style="margin-left: 8px"
                    alt="有人"
                />
                <img
                    v-if="b.statue === 3"
                    src="@/images/bed_out.svg"
                    width="30px"
                    style="margin-left: 8px"
                    alt="外出"
                />
                <div style="margin-left: 3px">{{ b.bedName }}</div>
              </div>
            </div>
          </el-card>

          <el-card shadow="hover" class="room" style="background-color: #409EFF">
            <span>楼梯</span>
            <div style="margin-top: 50%; margin-left: 23%">
              <img src="@/images/stairs.svg" width="40px" alt="楼梯" />
            </div>
          </el-card>
        </div>

        <div
            style="
            background-color: #409EFF;
            height: 50px;
            margin-top: 10px;
            margin-left: 10px;
            line-height: 50px;
          "
            v-if="record && record.room"
        >
          <span style="margin-left: 50%">走廊</span>
        </div>

        <div v-else>
          <el-empty description="未找到目标"></el-empty>
        </div>
      </div>

      <!-- 床位详细信息 Dialog -->
      <el-dialog
          title="床位信息"
          width="40%"
          v-model="dialogVisible"
          @close="closeDialog"
      >
        <el-descriptions
            border
            direction="horizontal"
            :column="2"
            style="margin-top: 15px"
        >
          <!-- 客户基本信息 -->
          <el-descriptions-item label="客户姓名" label-align="center" :span="1">
            {{ customerRecord.customerName }}
          </el-descriptions-item>
          <el-descriptions-item label="年龄" label-align="center" :span="1">
            {{ customerRecord.customerAge }}
          </el-descriptions-item>
          <el-descriptions-item label="性别" label-align="center" :span="1">
            <el-tag type="primary" v-if="customerRecord.customerSex === 0">男</el-tag>
            <el-tag type="success" v-if="customerRecord.customerSex === 1">女</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="身份证号" label-align="center" :span="1">
            {{ customerRecord.idcard }}
          </el-descriptions-item>

          <!-- 房间和床位信息 -->
          <el-descriptions-item label="房间号" label-align="center" :span="1">
            {{ customerRecord.roomNo }}
          </el-descriptions-item>
          <el-descriptions-item label="所属楼房" label-align="center" :span="1">
            {{ customerRecord.buildingNo }}
          </el-descriptions-item>
          <el-descriptions-item label="床号" label-align="center" :span="1">
            {{ customerRecord.bedId }}
          </el-descriptions-item>

          <!-- 入住和合同信息 -->
          <el-descriptions-item label="入住时间" label-align="center" :span="1">
            {{ formatDate(customerRecord.checkinDate) }}
          </el-descriptions-item>
          <el-descriptions-item label="合同到期时间" label-align="center" :span="1">
            {{ formatDate(customerRecord.expirationDate) }}
          </el-descriptions-item>

          <!-- 联系方式 -->
          <el-descriptions-item label="联系电话" label-align="center" :span="1">
            {{ customerRecord.contactTel }}
          </el-descriptions-item>
          <el-descriptions-item label="家属" label-align="center" :span="1">
            {{ customerRecord.familyMember }}
          </el-descriptions-item>

          <!-- 身心状况和注意事项 -->
          <el-descriptions-item label="身心状况" label-align="center" :span="2">
            {{ customerRecord.psychosomaticState }}
          </el-descriptions-item>
          <el-descriptions-item label="注意事项" label-align="center" :span="2">
            {{ customerRecord.attention }}
          </el-descriptions-item>

          <!-- 其他信息 -->
          <el-descriptions-item label="出生日期" label-align="center" :span="1">
            {{ formatDate(customerRecord.birthday) }}
          </el-descriptions-item>
          <el-descriptions-item label="身高" label-align="center" :span="1">
            {{ customerRecord.height }}
          </el-descriptions-item>
          <el-descriptions-item label="体重" label-align="center" :span="1">
            {{ customerRecord.weight }}
          </el-descriptions-item>
          <el-descriptions-item label="血型" label-align="center" :span="1">
            {{ customerRecord.bloodType }}
          </el-descriptions-item>
        </el-descriptions>
        <el-divider />
        <el-row style="margin-top: 5px">
          <el-col :span="10" :offset="21">
            <el-button @click="closeDialog" type="primary">关闭</el-button>
          </el-col>
        </el-row>
      </el-dialog>

      <!-- 外出人员信息 Dialog -->
      <el-dialog
          title="外出人员信息"
          width="40%"
          v-model="outwardDialogVisible"
          @close="closeOutwardDialog"
          v-if="outwardRecord && Object.keys(outwardRecord).length > 0"
      >
        <el-descriptions
            border
            direction="horizontal"
            :column="2"
            style="margin-top: 15px"
        >
          <el-descriptions-item label="备注" label-align="center" :span="1">
            {{ outwardRecord.remarks }}
          </el-descriptions-item>
          <el-descriptions-item label="外出事由" label-align="center" :span="1">
            {{ outwardRecord.outgoingreason }}
          </el-descriptions-item>
          <el-descriptions-item label="外出时间" label-align="center" :span="1">
            {{ formatDate(outwardRecord.outgoingtime) }}
          </el-descriptions-item>
          <el-descriptions-item label="预计回院时间" label-align="center" :span="1">
            {{ formatDate(outwardRecord.expectedreturntime) }}
          </el-descriptions-item>
          <el-descriptions-item label="实际回院时间" label-align="center" :span="1">
            {{ formatDate(outwardRecord.actualreturntime) }}
          </el-descriptions-item>
          <el-descriptions-item label="陪同人" label-align="center" :span="1">
            {{ outwardRecord.escorted }}
          </el-descriptions-item>
          <el-descriptions-item label="与老人关系" label-align="center" :span="1">
            {{ outwardRecord.relation }}
          </el-descriptions-item>
          <el-descriptions-item label="陪同人电话" label-align="center" :span="1">
            {{ outwardRecord.escortedtel }}
          </el-descriptions-item>
          <el-descriptions-item label="审批状态" label-align="center" :span="1">
            {{ getAuditStatusText(outwardRecord.auditstatus) }}
          </el-descriptions-item>
          <el-descriptions-item label="审批人" label-align="center" :span="1">
            {{ outwardRecord.auditperson }}
          </el-descriptions-item>
          <el-descriptions-item label="审批时间" label-align="center" :span="1">
            {{ formatDate(outwardRecord.audittime) }}
          </el-descriptions-item>
        </el-descriptions>
        <el-divider />
        <el-row style="margin-top: 5px">
          <el-col :span="10" :offset="21">
            <el-button @click="closeOutwardDialog" type="primary">关闭</el-button>
          </el-col>
        </el-row>
      </el-dialog>
      <el-divider />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import http from '@/axios/http';
import { Plus, Search } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';

// 数据模型
const keyword = ref('');
const round = ref('1');
const record = ref(null);
const dialogVisible = ref(false);
const bedRecord = ref({});
const customerRecord = ref({});
const emergencyRecord = ref({});
const searchKeyword = ref('');



let pageNum = ref(1);
let pageSize = ref(10);
let size = 10;

// 当前页码信息
let pageContains = ref({});

// 楼层选项
const floors = [
  { label: '一楼', value: '1' },
  { label: '二楼', value: '2' },
];
// 外出人员信息相关
const outwardDialogVisible = ref(false);
const outwardRecord = ref({});


// 打开床位详情 Dialog
const openInfoDialog = (data) => {
  // 检查传入的 data 是否有效
  console.log('传入的 data:', data);
  if (!data || !data.id) {
    console.error('传递的 data 参数无效或缺少 id:', data);
    ElMessage.error('无法打开床位详情，请检查传入的数据！');
    return;
  }

  // 判断床位状态，如果是外出状态则打开外出人员信息对话框
  if (data.statue === 3) {
    openOutwardDialog(data.id);
    return;
  }

  // 打印请求参数以便调试
  console.log('发送的请求参数:', { id: data.id });

  // 发送 POST 请求到后端
  http.post('/lyy/get_customer_data', { id: data.id })
      .then((res) => {
        console.log('后端返回的数据:', res.data);

        // 检查返回结果是否成功
        let result = res.data;
        if (result.result === 'success') {
          // 验证返回数据结构是否符合预期
          if (!result.data || result.data.length === 0) {
            console.error('后端返回的数据为空:', result);
            ElMessage.error('床位为空！');
            return;
          }

          // 获取第一个客户数据
          const customer = result.data[0];

          // 更新前端状态
          customerRecord.value = customer;
          bedRecord.value = {
            id: customer.bedId,
            roomNo: customer.roomNo,
            buildingNo: customer.buildingNo,
          };
          emergencyRecord.value = {
            contact: customer.contactTel,
            familyMember: customer.familyMember,
          };

          // 显示对话框
          dialogVisible.value = true;
        } else {
          // 处理后端返回的错误信息
          console.error('后端返回错误:', result.error);
          ElMessage.error(result.error || '未知错误');
        }
      })
      .catch((error) => {
        // 捕获网络或请求错误
        console.error('请求后端接口失败:', error);
        ElMessage.error('请求失败，请检查网络连接或稍后再试！');
      });
};

// 数据处理函数
const processData = (data, selectedFloor) => {
  const groupedData = data.reduce((acc, item) => {
    if (item.roomNo.toString().startsWith(selectedFloor)) {
      const roomName = item.roomNo.toString();
      if (!acc[roomName]) {
        acc[roomName] = { roomName, bed: [] };
      }
      acc[roomName].bed.push({
        id: item.id,
        bedName: item.bedNo,
        statue: item.bedStatus,
      });
    }
    return acc;
  }, {});

  return Object.values(groupedData);
};

// 获取床位可视化数据
const getDesign = async () => {
  console.log('当前选择的楼层:', round.value);
  console.log('搜索关键词:', searchKeyword.value);
  const requestParams = {
    floor: round.value,
    keyword: searchKeyword.value,
  };
  console.log('发送的请求参数:', requestParams);
  try {
    const resp = await http.post('/lyy/get_bed_design', requestParams);
    console.log('后端返回的数据:', resp.data.data);
    // 处理数据并更新记录
    const processedData = processData(resp.data.data || [], round.value);
    record.value = { room: processedData };
    console.log('处理后的数据:', record.value);
  } catch (error) {
    console.error('获取床位数据失败:', error);
    record.value = null;
  }
};

// 关闭 Dialog
const closeDialog = () => {
  dialogVisible.value = false;
  bedRecord.value = {};
  customerRecord.value = {};
};

// 格式化日期
const formatDate = (date) => {
  if (!date) return '-';
  let d;
  if (typeof date === 'number') {
    d = new Date(date);
  } else {
    d = new Date(date);
  }
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(
      d.getDate()
  ).padStart(2, '0')}`;
};

// 打开外出人员信息 Dialog
const openOutwardDialog = (bedId) => {
  http.post('/lyy/get_outward_info', { bedId })
      .then((res) => {
        console.log('后端返回的外出人员信息:', res.data);
        if (res.data.result === 'success' && res.data.data.length > 0) {
          outwardRecord.value = res.data.data[0];
          console.log('设置后的 outwardRecord:', outwardRecord.value);
          outwardDialogVisible.value = true;
        } else {
          ElMessage.error(res.data.error || '获取外出人员信息失败');
        }
      })
      .catch((error) => {
        console.error('请求外出人员信息失败:', error);
        ElMessage.error('请求失败，请检查网络连接或稍后再试！');
      });
};

// 关闭外出人员信息 Dialog
const closeOutwardDialog = () => {
  outwardDialogVisible.value = false;
  outwardRecord.value = {};
};

// 获取审批状态文本
const getAuditStatusText = (status) => {
  switch (status) {
    case 0:
      return '已提交';
    case 1:
      return '同意';
    case 2:
      return '拒绝';
    default:
      return '未知状态';
  }
};

// 处理每页显示数量变化
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  getbedDetails();
};

// 处理页码变化
const handlePageChange = (newPage) => {
  pageNum.value = newPage;
  getbedDetails();
};

// 生命周期钩子
onMounted(() => {
  getDesign();
});
</script>

<style lang="less">
.show_box {
  display: flex;
  flex-wrap: wrap;
  gap: 5px; /* 减小房间之间的间距 */
  width: 1200px;
  padding: 5px; /* 减小容器内边距 */
}

.room {
  width: 110px; /* 减小房间卡片的宽度 */
  height: 25vh; /* 减小房间卡片的高度 */
  margin-bottom: 10px; /* 减小底部间距 */
  transition: transform 0.3s ease;
}

.room:hover {
  transform: scale(1.05);
}

.bed_container {
  cursor: pointer;
  margin-left: 10px; /* 减小床位容器的左边距 */
  margin-top: 4px; /* 减小床位容器的上边距 */
}

/* 响应式设计 */
@media (max-width: 768px) {
  .show_box {
    justify-content: center;
  }

  .room {
    width: 100px; /* 小屏幕下进一步减小房间卡片宽度 */
    height: 20vh; /* 小屏幕下进一步减小房间卡片高度 */
  }
}
</style>